package com.zzyl.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.UserDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.User;
import com.zzyl.entity.UserRole;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.UserService;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.utils.NoProcessing;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.RoleVo;
import com.zzyl.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    UserRoleMapper userRoleMapper;


    /**
     * 用户分页
     *
     * @param userDto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResponse<UserVo> findUserVoPageResponse(UserDto userDto, int pageNum, int pageSize) {
        //userDto传入特殊处理后的字符串,具体是去掉多余的0,三个一组
        if (!EmptyUtil.isNullOrEmpty(userDto.getDeptNo())) {
            userDto.setDeptNo(NoProcessing.processString(userDto.getDeptNo()));
        }
        //分页
        PageHelper.startPage(pageNum, pageSize);
        // 查询
        Page<User> userPage = userMapper.findUserVoPageResponse(userDto);

        // 转换成用户Vo集合
        PageResponse<UserVo> userVoPageResponse = PageResponse.of(userPage, UserVo.class);
        //判断Records数据列表是否为空
        if (!EmptyUtil.isNullOrEmpty(userVoPageResponse.getRecords())) {
            //提取用户id 列表，用stream流提取，转换成Long集合
            List<Long> collect = userVoPageResponse.getRecords().stream().map(UserVo::getId).collect(Collectors.toList());
            //根据用户id查询用户角色信息 转换成RoleVo集合
            List<RoleVo> roleVoList = roleMapper.findRoleVoListInUserId(collect);

            // 遍历用户集合，根据用户id查询用户角色信息 封装到用户Vo集合中
            userVoPageResponse.getRecords().forEach(userVo -> {
                Set<String> roleVoIds = new HashSet<>();
                Set<String> roleVonames = new HashSet();
                roleVoList.forEach(r -> {
                    if (String.valueOf(userVo.getId()).equals(r.getUserId())) {
                        roleVoIds.add(String.valueOf(r.getId()));
                        roleVonames.add(r.getRoleName());
                    }
                });
                // 设置角色id集合
                userVo.setRoleVoIds(roleVoIds);
                // 设置角色名称集合
                userVo.setRoleLabels(roleVonames);
            });

        }
        return userVoPageResponse;
    }
    /**
     * 添加用户
     *
     *
     * @param userDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserVo addUser(UserDto userDto) {
        User user = BeanUtil.toBean(userDto, User.class);
        user.setDataState("0");
        user.setUsername(user.getEmail());
        String password = "888itcast.CN764%...";
        user.setPassword(BCrypt.hashpw(password, BCrypt.gensalt()));
        userMapper.createUser(user);
        List<UserRole> list = new ArrayList<>();
        Set<String> roleVoIds = userDto.getRoleVoIds();
        roleVoIds.forEach(roleVoId -> {
            UserRole build = UserRole.builder()
                    .dataState(SuperConstant.DATA_STATE_0)
                    .userId(user.getId())
                    .roleId(Long.valueOf(roleVoId))
                    .build();
            list.add(build);
            userRoleMapper.insetr(list);
        });
        return BeanUtil.toBean(user, UserVo.class);
    }

    /**
     * 启用-禁用
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public Boolean isEnable(Long id, String status) {
        userMapper.isEnable(id, status);
        return true;
    }

    /**
     * 删除用户
     *
     * @param userIds
     * @return
     */
    @Override
    public Boolean remove(String userIds) {
        User user = userMapper.looks(userIds);
        if (user == null || user.getDataState().equals(SuperConstant.DATA_STATE_0)) {
            throw new RuntimeException("该用户已禁用，不能删除");
        }
        userMapper.deleteUserById(userIds);
        return true;
    }

    /**
     * 重置密码
     *
     * @param userId
     * @return
     */
    @Override
    public Boolean resetPasswords(Long userId) {
        String password = "888itcast.CN764%...";
        userMapper.resetPasswords(userId, password);
        return true;
    }

    /**
     * 用户列表
     *
     * @param userDto
     * @return
     */
    @Override
    public UserVo userList(UserDto userDto) {
        User user = BeanUtil.toBean(userDto, User.class);
        userMapper.look(user);
        return BeanUtil.toBean(user, UserVo.class);
    }


    /**
     * 修改用户
     *
     * @param userDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateUser(UserDto userDto) {
        String dataState = userDto.getDataState();
        if (dataState.equals(SuperConstant.DATA_STATE_1)) {
            throw new RuntimeException("该用户已禁用，不能修改");
        }
        User user = BeanUtil.toBean(userDto, User.class);
        userMapper.updateUser(user);

        Long id = user.getId();
        userRoleMapper.del(id);

        List<UserRole> list = new ArrayList<>();
        Set<String> roleVoIds = userDto.getRoleVoIds();
        roleVoIds.forEach(roleVoId -> {
            UserRole build = UserRole.builder()
                    .dataState(SuperConstant.DATA_STATE_0)
                    .userId(user.getId())
                    .roleId(Long.valueOf(roleVoId))
                    .build();
            list.add(build);
            userRoleMapper.insetr(list);
        });
        return true;
    }


}
